package com.aloudmeta.grpc.client;

import com.aloudmeta.grpc.demo.GreetingRequest;
import com.aloudmeta.grpc.demo.GreetingResponse;
import com.aloudmeta.grpc.demo.GreetingServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Metadata;
import io.grpc.stub.MetadataUtils;

/**
 * huaixin 2022/1/27 11:44 PM
 */
public class GreetingClient {

    private static Metadata.Key<String> GRPC_TENANT_ID =
            Metadata.Key.of("TENANT_ID", Metadata.ASCII_STRING_MARSHALLER);

    public static void main(String[] args) {
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8080)
                .usePlaintext()
                .build();

        GreetingServiceGrpc.GreetingServiceBlockingStub stub = buildStub(channel);

        GreetingRequest request = GreetingRequest.newBuilder().build();
        GreetingResponse response = stub.greeting(request);
        System.out.println(response.getGreeting());
    }

    private static GreetingServiceGrpc.GreetingServiceBlockingStub buildStub(ManagedChannel channel) {
        GreetingServiceGrpc.GreetingServiceBlockingStub stub = GreetingServiceGrpc.newBlockingStub(channel);

        Metadata extraHeaders = new Metadata();
        extraHeaders.put(GRPC_TENANT_ID, "aloudata");
        stub = stub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(extraHeaders));
        return stub;
    }
}
